#include "Texture.h"
#include <gl\glew.h>
#include "ImageLoading.h"
#include <stdio.h>


Texture::Texture() : Resource()
{

}
Texture::~Texture()
{
	Dispose();
}

void Texture::Dispose()
{
	if(IsAllocated())
	{
		glDeleteTextures(1,&texture);
	}
}


void Texture::Bind()
{
	if(IsAllocated() == false)
	{
		glGenTextures(1,&texture);
		SetAllocated();
	}

	glBindTexture(GL_TEXTURE_2D,texture);
}

void Texture::Unbind()
{
	glBindTexture(GL_TEXTURE_2D,0);
}
void Texture::LoadFromFile(const char * fileName)
{
	FILE * f = fopen(fileName,"rb");
	int x,y,ch;
	void * data = stbi_load_from_file(f,&x,&y,&ch,4);
	fclose(f);

	GLint format;
	if(ch == 3)
		format = GL_RGBA;
	else 
		format = GL_RGBA;

	glTexImage2D(GL_TEXTURE_2D,0,format,x,y,0,format,GL_UNSIGNED_BYTE,data);
	stbi_image_free(data);
}

void Texture::SetActiveSlot(unsigned short slot)
{
	glActiveTexture(GL_TEXTURE0 + slot);
}

void Texture::SetProperty(TexProp prop,TexVal val)
{
	glTexParameteri(GL_TEXTURE_2D,prop,val);
}

void Texture::BindUniformToSlot(int uniformId,unsigned int slot)
{
	glUniform1i(uniformId,slot);
}

void Texture::GerateMipMaps()
{
	glGenerateMipmap(GL_TEXTURE_2D);
}

unsigned int Texture::GetGLRes()
{
	return texture;
}

void Texture::InitTexture(unsigned int width,unsigned int height)
{
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,nullptr);
}